<template>
    <div class="title">修改密码</div>
    <el-form :model="formData" :rules="rules" label-width="auto" style="max-width: 400px" ref="formRef">
        <el-form-item label="原密码" prop="password">
            <el-input v-model="formData.password" type="password">

            </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password2">
            <el-input v-model="formData.password2" type="password">

            </el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="password3">
            <el-input v-model="formData.password3" type="password">

            </el-input>

        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm">
                立即修改
            </el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { reactive } from 'vue'
import { editpwd } from '../../api/account'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const formData = reactive({
    password: '',
    password2: '',
    password3: '',
})
const rules = reactive({
    password: [
        { required: true, message: '请输入老密码', trigger: 'blur' },
        { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
    ],
    password2: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
    ],
    password3: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
    ],
})

const submitForm = async () => {

    try {
        // 检查旧密码
       
        const editRes = await editpwd({
            newPwd: formData.password2,
            id: JSON.parse(sessionStorage.getItem('id')),
            newPwd1: formData.password3,
            oldPwd: formData.password
        });

        if (editRes.code === 0) {
            ElMessage.success('密码修改成功');
            // 清空表单
            router.push('/login');
        } else {
            ElMessage.error(editRes.msg || '密码修改失败');
        }
    } catch (error) {
        ElMessage.error('请求异常，请检查网络');
        console.error(error);
    }
};
</script>

<style lang="scss" scoped>
.title {
    width: 100%;
    height: 50px;
    font-size: 20px;
    color: #333;
    line-height: 50px;
    padding-left: 20px;
    text-align: left;
    border-bottom: 1px solid #dcdfe6;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-form--label-right {
    padding: 10px 40px;
}

.el-button--primary {
    margin-left: 100px;
}
</style>